package com.feinno.module.security.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.feinno.framework.common.web.AbstractEntityController;
import com.feinno.module.security.domain.User;
import com.feinno.module.security.service.UserService;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 * @author zhangpu
 */
@Controller
public class LoginController extends
		AbstractEntityController<User, UserService> {

	private static final Logger logger = LoggerFactory
			.getLogger(LoginController.class);

	/**
	 * GET访问，直接进入登陆界面：/admin/login.jsp
	 * 
	 * @return
	 */
	@RequestMapping(value = "/admin/login")
	public String login(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			// 如果已经登录的情况，直接回到主框架界面
			return "/admin/index";
		} else {
			// 如果没有登录的首次进入登录界面，直接返回到登录界面。
			saveMessage(request, "会话失效，请登录");
			return "/admin/login";
		}
	}

	@RequestMapping(value = "/admin/onLoginSuccess")
	public String onLoginSuccess(HttpServletRequest request) {
		logger.debug("OnLoginSuccess, redirect to /admin/index.jsp");
		return "redirect:/admin/index.jsp";
	}

	@RequestMapping(value = "/admin/onLoginFailure")
	public String onLoginFailure(HttpServletRequest request) {
		logger.debug("OnLoginFailure");
		// 获取Shiro的错误信息
		String obj = request
				.getParameter(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String msg = "";
		if (obj != null) {
			if ("org.apache.shiro.authc.UnknownAccountException".equals(obj)) {
				msg = "未知帐号错误";
			} else if ("org.apache.shiro.authc.IncorrectCredentialsException"
					.equals(obj)) {
				msg = "密码错误";
			} else if ("com.feinno.module.security.shiro.exception.InvaildCaptchaException"
					.equals(obj)) {
				msg = "验证码错误";
			} else if ("org.apache.shiro.authc.AuthenticationException"
					.equals(obj)) {
				msg = "认证失败";
			} else {
				msg = "系统内部错误,请重试";
			}
			logger.debug(msg + " --> " + obj);
			saveMessage(request, msg);
		}
		return "redirect:/admin/login.mvc";
	}

	/**
	 * 注销后，由安全框架注销后redirect到这个进行后续清理。 默认无处理，直接返回登录界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/onLogout")
	public String onLogout(HttpServletRequest request) {
		logger.debug("onLogout, redirect to login page: /admin/login.jsp");
		return "/admin/login";
	}

	/**
	 * 会话过期，或未授权访问的情况的回调，框架配置中没有使用，而是使用遇到未授权访问直接注销返回到登录界面。
	 * 这里保留是为了，如果有需求可以配置框架返回到这里进行后续处理。
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/admin/onUnauthorized")
	public String onUnauthorized(HttpServletRequest request) {
		saveMessage(request, "没有授权的访问");
		return "/admin/error";
	}

}
